package controller;

import helper.ApkPureHelper;
import org.apache.logging.log4j.util.Strings;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletResponse;

@Controller
@RequestMapping("/apk/")
public class ApkPureController {
    /**
     * 通过来源url，获得cdn下载链接
     * apkNode
     * @param srcUrl
     * @return
     */
    @RequestMapping("downUrl4node")
    @ResponseBody
    public String getDownloadUrl(String srcUrl) throws Exception{
        String downLoadUrl = ApkPureHelper.getDownLoadUrl(srcUrl);
        if (Strings.isBlank(downLoadUrl)) {
            downLoadUrl = srcUrl;
        }
        return downLoadUrl;
    }

    @RequestMapping("down")
    @ResponseBody
    public String redirectDownPage(String srcUrl) throws Exception{
        return getRedirectHtml(ApkPureHelper.getUrlFromAPKNode(srcUrl));
    }

    private String getRedirectHtml(String targetUrl) {
        String html = "<html>\n" +
                "<head>\n" +
                "<meta http-equiv=\"Content-Type\" content=\"text/html; charset=utf-8\">\n" +
                "<title>开始下载</title>\n" +
                "</head>\n" +
                "<body>\n" +
                "    <form name=loading> \n" +
                "    　 <p align=center> <font color=\"#0066ff\" size=\"4\">3秒后开始下载...</font>\n" +
                "        <script>　 \n" +
                "            var bar=0;\n" +
                "            count(); \n" +
                "            function count(){　 \n" +
                "                bar=bar+2;\n" +
                "                if (bar<99)　 {\n" +
                "                    setTimeout(\"count()\",100);\n" +
                "                }　 else　 {\n" +
                "                    window.location = \"xxxxx\";\n" +
                "                }　 \n" +
                "            }\n" +
                "        </script> \n" +
                "    　</p> \n" +
                "    </form>\n" +
                "    <p align=\"center\">\n" +
                "    如果您的浏览器不支持跳转,<a style=\"text-decoration: none\" href=\"xxxxx\"><font color=\"#FF0000\">请点这里</font></a>.</p>\n" +
                "    </body>\n" +
                "</html>";
        html = html.replaceAll("xxxxx", targetUrl);
        return html;
    }
}
